package clerk

import (
	"crypto/md5"
	"encoding/hex"
	"end/config"
	"end/entry"
	"end/httpEntry"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

type AddRequest struct {
	Name      string `json:"name" binding:"required"`
	Password  string `json:"password" binding:"required"`
	Starttime string `json:"starttime" binding:"required"`
	Endtime   string `json:"endtime" binding:"required"`
}

type DelRequest struct {
	Id int `json:"id" binding:"required"`
}

type UserDto struct {
	Id                int       `json:"id" gorm:"column:id"`
	Name              string    `json:"name" gorm:"column:name"`
	Nick              string    `json:"nick" gorm:"column:nick"`
	Img               string    `json:"img" gorm:"column:img"`
	Age               int       `json:"age" gorm:"column:age"`
	Phone             string    `json:"phone" gorm:"column:phone"`
	PoliticalOutlook  string    `json:"political-outlook" gorm:"column:political_outlook"`
	Address           string    `json:"address" gorm:"column:address"`
	PersonalSignature string    `json:"personal_signature" gorm:"column:personal_signature"`
	CreateTime        time.Time `json:"createtime" gorm:"column:createtime"`
	UpdateTime        time.Time `json:"updatetime" gorm:"column:updatetime"`
}

func (UserDto) TableName() string {
	return "user"
}

type Dto struct {
	ID         int       `json:"id" gorm:"column:id"`
	UserID     int       `json:"userid" gorm:"column:userid"`
	StartTime  string    `json:"starttime" gorm:"column:starttime"`
	EndTime    string    `json:"endtime" gorm:"column:endtime"`
	CreateTime time.Time `json:"createtime" gorm:"column:createtime"`
	User       UserDto   `json:"user" gorm:"foreignkey:UserID"`
}

func (Dto) TableName() string {
	return "clerk"
}

// IsClerk 判断是否是店员
func IsClerk(r *gin.Engine) {
	r.GET("/clerk/is", httpEntry.LoginMiddleware(), httpEntry.ClerkMiddleware(), func(context *gin.Context) {
		context.JSON(http.StatusOK, httpEntry.BaseResponse{
			Code:    200,
			Message: "我是店员",
		})
	})
}

// AddClerk 增加店员
func AddClerk(r *gin.Engine) {
	r.POST("/clerk/add", httpEntry.LoginMiddleware(), httpEntry.BusinessMiddleware(), func(context *gin.Context) {
		userinfo := context.MustGet("userinfo").(config.UserInfo)
		db := config.GetDb()
		business := entry.Business{}
		result := db.Where("id = ? ", userinfo.Id).First(&business)

		if result.Error != nil {
			context.JSON(http.StatusOK, httpEntry.BaseResponse{
				Code:  10005,
				Error: httpEntry.ERROR10005,
			})
			return
		}
		if business.Status != config.STATUS2 {
			context.JSON(http.StatusOK, httpEntry.BaseResponse{
				Code:  10004,
				Error: httpEntry.ERROR10004,
			})
		}

		// 检测参数是否足够
		var request AddRequest
		err := context.ShouldBind(&request)

		if err != nil {
			context.JSON(http.StatusOK, httpEntry.BaseResponse{
				Code:  10006,
				Error: httpEntry.ERROR10006,
			})
			return
		}
		// 创建一个MD5哈希对象
		hashes := md5.New()
		// 将字符串写入哈希对象
		hashes.Write([]byte(request.Password))
		// 计算哈希值并将其转换为16进制字符串
		hashInBytes := hashes.Sum(nil)
		hashPassword := hex.EncodeToString(hashInBytes)
		var user entry.User
		result = db.Where("name = ? AND password = ?", request.Name, hashPassword).First(&user)
		// 检查错误
		if result.Error != nil {
			context.JSON(http.StatusOK, httpEntry.BaseResponse{
				Code:  10007,
				Error: httpEntry.ERROR10007,
			})
			return
		}
		// 检测这个用户是否已经是商家
		var userBusiness entry.Business
		result = db.Where("userid = ?", user.ID).First(&userBusiness)
		// 如果存在，不会报错
		if result.Error == nil {
			context.JSON(http.StatusOK, httpEntry.BaseResponse{
				Code:  10007,
				Error: "已经是商家了",
			})
			return
		}

		clerk := entry.Clerk{
			UserID:     user.ID,
			BusinessID: userinfo.Id,
			StartTime:  request.Starttime,
			EndTime:    request.Endtime,
		}
		clerk.CreateTime = time.Now()
		result = db.Create(&clerk)
		// 检查错误
		if result.Error != nil {
			context.JSON(http.StatusOK, httpEntry.BaseResponse{
				Code:  10008,
				Error: httpEntry.ERROR10008,
			})
			return
		}
		context.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "成功",
			"clerk":   clerk.ID,
		})
	})
}

// AllClerk 查询全部的店员
func AllClerk(r *gin.Engine) {
	r.GET("/clerk/all", httpEntry.LoginMiddleware(), httpEntry.BusinessMiddleware(), func(context *gin.Context) {
		userinfo := context.MustGet("userinfo").(config.UserInfo)
		db := config.GetDb()
		var clerks []Dto
		db.Preload("User").Where("businessid = ?", userinfo.Id).Find(&clerks)
		context.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "成功",
			"data":    clerks,
		})
	})
}

// DelClerk 删除店员
func DelClerk(r *gin.Engine) {
	r.POST("/clerk/del", httpEntry.LoginMiddleware(), httpEntry.BusinessMiddleware(), func(context *gin.Context) {
		userinfo := context.MustGet("userinfo").(config.UserInfo)
		var delRequest DelRequest
		err := context.ShouldBind(&delRequest)
		if err != nil {
			context.JSON(http.StatusOK, httpEntry.BaseResponse{
				Code:  10006,
				Error: httpEntry.ERROR10006,
			})
			return
		}
		// 判断这个店员是不是自己的
		var clerk entry.Clerk
		db := config.GetDb()
		result := db.Where("businessid = ?", userinfo.Id).First(&clerk)
		if result.Error != nil {
			context.JSON(http.StatusOK, httpEntry.BaseResponse{
				Code:  10005,
				Error: httpEntry.ERROR10005,
			})
			return
		}
		result = db.Delete(&entry.Clerk{}, delRequest.Id)
		if result.Error != nil {
			context.JSON(http.StatusOK, httpEntry.BaseResponse{
				Code:  10009,
				Error: httpEntry.ERROR10009,
			})
			return
		}
		context.JSON(http.StatusOK, httpEntry.BaseResponse{
			Code:    200,
			Message: "删除成功",
		})
	})
}

func GetBusiness(r *gin.Engine) {
	r.GET("/clerk/business/info", httpEntry.LoginMiddleware(), httpEntry.ClerkMiddleware(), func(context *gin.Context) {
		userinfo := context.MustGet("userinfo").(config.UserInfo)
		var clerk entry.Clerk
		db := config.GetDb()
		result := db.Model(&clerk).Where("id = ?", userinfo.Id).First(&clerk)
		if result.Error != nil {
			context.JSON(http.StatusOK, gin.H{
				"code":  10031,
				"error": "店员身份错误",
			})
			return
		}
		var business entry.Business
		result = db.Model(&business).Where("id = ?", clerk.BusinessID).First(&business)
		if result.Error != nil {
			context.JSON(http.StatusOK, gin.H{
				"code":  10032,
				"error": "商家已注销",
			})
			return
		}
		context.JSON(http.StatusOK, gin.H{
			"code": 200,
			"data": business,
		})
	})
}
